package org.xhnews.parsers;

import java.io.InputStream;
import java.util.Vector;

import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.MessageItem;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class MessagePullXMLParser {
	// 解析频道列表
	public static Vector readMessages(InputStream inputStream,
			String inputEncoding) {
		try {
			// 创建Pull解析
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			XmlPullParser pullParser = pullParserFactory.newPullParser();
			// 解析XML
			pullParser.setInput(inputStream, inputEncoding);
			// 开始
			int eventType = pullParser.getEventType();
			Vector messages = new Vector();
			MessageItem msg = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				// 文档开始
				case XmlPullParser.START_DOCUMENT:

					break;
				// 节点开始
				case XmlPullParser.START_TAG:
					try {
						if ("Msg".equals(nodeName)) {
							String id = pullParser.getAttributeValue(null,
									"TID");
							String title = pullParser.getAttributeValue(null,
									"Title");
							String sendername = pullParser.getAttributeValue(
									null, "SName");
							String date = pullParser.getAttributeValue(null,
									"Date");
							String attach = pullParser.getAttributeValue(null,
									"Attach");
							if (id != null) {
								msg = new MessageItem();
								msg.setId(id);
								msg.setSenderName(sendername);
								msg.setDate(date);
								msg.setTitle(title);
								msg.setAttach(attach);
								messages.addElement(msg);
							}
						}
					} catch (Exception e) {

					}
					break;
				// 节点结束
				case XmlPullParser.END_TAG:
					break;
				}
				eventType = pullParser.next();
			}// end while
			return messages;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			return null;
		}
	}
}
